import * as Swiper from 'swiper'
import browser = require('./ext_pyfail')
import { DB } from '../share/share'
import uuid from '../share/uuid'
import date from '../share/time'
import initFetch from '../share/fetch_init'
import * as JSZip from 'jszip'

let Realuuid = uuid()
let Realdate = date
let port = browser.runtime.connect({name: 'test'})
port.postMessage('bud pages 加载完成')
let HTMLEle = {
  progress: document.getElementById('processing')
}

// zip
let zip = new JSZip()
// 初始添加

async function making () {
  await initFetch()

  const containerXML = await DB.template.where('name').equals('container.xml').first()
  zip.file(containerXML.path.substr(1), containerXML.source)
  const notereplaceJS = await DB.template.where('name').equals('notereplace.js').first()
  zip.file(notereplaceJS.path.substr(1), notereplaceJS.source)
  const styleCSS = await DB.template.where('name').equals('style.css').first()
  zip.file(styleCSS.path.substr(1), styleCSS.source)
  const mimetype = await DB.template.where('name').equals('mimetype').first()
  zip.file(mimetype.path.substr(1), mimetype.source)

  let galleryTop = document.getElementById('gallery-top')
  let galleryThumbsObject = document.getElementById('gallery-thumbs')
  class ImageDiv {
    creat (
      className: string = 'swiper-slide',
      img: string = '#',
      title: string = '#') {

      let div = document.createElement('div')
      div.className = className
      div.title = title
      div.style.backgroundImage = `url('${img}')`
      return div
    }
  }
  class ContentItemInput {
    creat (
      type: string = 'text',
      placeholder: string = '当前世界线：') {

      let input = document.createElement('input')
      placeholder += Math.random().toFixed(5)
      input.type = type
      input.placeholder = placeholder
      return input
    }
  }
  let colorSlide = `
      <div class="swiper-slide">
        <h1>彩页</h1>
        <div class="img" style="height:100%;"></div>
        <div style="height:4em;">
          <textarea name="inori_color" class="color" placeholder="填写彩页文字"></textarea>
        </div>
        <div class="dilan">
          <div class="addButton" id = 'addColor'>还有彩页！</div>
          <div class="color_last_button" id = 'addColorLast'>next</div>
        </div>
      </div>`.trim()
  let contentSlide = `
      <div class="swiper-slide">
        <h1>目录</h1>
        <div class="contentList">
          <form>
            <!-- value变动的时候就添加一个，固定高度 -->
            <div class="contentItemWrap">
              <input type="text" placeholder="填写世界线："/>
            </div>
          </form>
        </div>
        <div class="dilan">
          <div class="submit" id = 'addContents'>填完收工</div>
        </div>
      </div>`.trim()

  await DB.allIMG.each((img) => {
    let div = new ImageDiv().creat('swiper-slide', URL.createObjectURL(img.source), img.name)
    let divClone = new ImageDiv().creat('swiper-slide', URL.createObjectURL(img.source), img.name)
    galleryThumbsObject.firstElementChild.appendChild(div)
    galleryTop.firstElementChild.appendChild(divClone)
  })

  let galleryTopObj = new Swiper('.gallery-top', {
    spaceBetween: 10,
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev'
    },
    nested: true
  })
  let galleryThumbsObj = new Swiper('.gallery-thumbs', {
    spaceBetween: 10,
    centeredSlides: true,
    slidesPerView: 'auto',
    touchRatio: 0.2,
    slideToClickedSlide: true,
    zoom: true,
    nested: true
  })
  let containerForm = new Swiper('.swiper-container-form', {
    spaceBetween: 10,
    nested: true,
    allowTouchMove: false,
    on: {
      init: function () {
        let img = galleryThumbsObj.slides[galleryThumbsObj.activeIndex].style.backgroundImage
        let clickNext = this.slides[this.activeIndex].getElementsByClassName('img')
        if (clickNext !== null && clickNext.length > 0) clickNext[0].style.backgroundImage = img
      }
    }
  })
  // debug用 ↓
  Object.defineProperty(window, 'containerForm', {value: containerForm})
  // 添加完了内容就进行跳转
  let swiperH = window.swiperH as Swiper
  swiperH.slideNext()

  galleryTopObj.controller.control = galleryThumbsObj
  galleryThumbsObj.controller.control = galleryTopObj
  galleryThumbsObj.on('slideChange', () => {
    let img = galleryThumbsObj.slides[galleryThumbsObj.activeIndex].style.backgroundImage
    let clickNext = containerForm.slides[containerForm.activeIndex].getElementsByClassName('img')
    if (clickNext !== null && clickNext.length > 0) clickNext[0].style.backgroundImage = img
  })
  containerForm.on('slideChange', () => {
    let img = galleryThumbsObj.slides[galleryThumbsObj.activeIndex].style.backgroundImage
    let clickNext = containerForm.slides[containerForm.activeIndex].getElementsByClassName('img')
    if (clickNext !== null && clickNext.length > 0) clickNext[0].style.backgroundImage = img
  })

  // slide跳转控制
  document.getElementsByClassName('swiper-container-form')[0].addEventListener('click', async (event) => {
    let target = event.target as typeof event.target & HTMLDivElement

    // build Epub 逻辑
    async function addCover () {
      // 修改图片name，储存用作文件名
      let activeTitle = galleryTopObj.slides[galleryTopObj.activeIndex].title
      let activeImg = await DB.allIMG.where('name').equals(activeTitle).first()
      activeImg.name = 'cover'
      await DB.allIMG.put(activeImg)

      // 定义附加字符串
      let manifest = `<item id="cover.xhtml" href="Text/cover.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="cover.xhtml"/>`
      let ncx = `<navPoint id="cover" playOrder="0">
                   <navLabel>
                     <text>封面</text>
                   </navLabel>
                   <content src="Text/cover.xhtml"/>
                 </navPoint>`.trim()

      // 强制赋值算是做一次初始化
      await DB.tempOrder.put({name: 'play', source: 1})
      await DB.tempOrder.put({name: 'sec', source: 1})
      await DB.tempOrder.put({name: 'color', source: 1})
      await DB.XMLGen.put({name: 'opfSpine', source: ''})
      await DB.XMLGen.put({name: 'opfManifest', source: ''})
      await DB.XMLGen.put({name: 'ncx', source: ''})

      // 尾添相关定义
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = spine
      })
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = manifest
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source = ncx
      })

      // xmlgen添加完了就添加对应的zipfile
      const coverXHTML = await DB.template.where('name').equals('cover.xhtml').first()
      zip.file(coverXHTML.path.substr(1), coverXHTML.source)
    }

    async function addCoverAlt () {
      // 图片改名
      let activeTitle = galleryTopObj.slides[galleryTopObj.activeIndex].title
      let activeImg = await DB.allIMG.where('name').equals(activeTitle).first()
      activeImg.name = 'coverAlt'
      await DB.allIMG.put(activeImg)

      // 读取当前播放顺序
      let playOrder = await DB.tempOrder.get('play').then((item) => item.source)

      let manifest = `<item id="coverAlt.xhtml" href="Text/coverAlt.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="coverAlt.xhtml"/>`
      let ncx = `<navPoint id="coverAlt" playOrder="${playOrder}">
                   <navLabel>
                     <text>封面</text>
                   </navLabel>
                   <content src="Text/coverAlt.xhtml"/>
                 </navPoint>`.trim()

      // 尾添定义
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = value.source += manifest
      })
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = value.source += spine
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source += ncx
      })
      // xmlgen添加完了就添加对应的zipfile
      const coverAltXHTML = await DB.template.where('name').equals('coverAlt.xhtml').first()
      zip.file(coverAltXHTML.path.substr(1), coverAltXHTML.source)

      // 自增order
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })
    }

    async function addMetadate () {
      const MetaList: HTMLCollectionOf<HTMLInputElement> = containerForm.slides[ containerForm.activeIndex ]
                                                        .getElementsByTagName('input')
      let type = {
        title: 'inori_title',
        author: 'inori_author',
        maker: 'inori_maker',
        desc: 'inori_desc'
      } as {
        [indes: string]: string
      }
      for (const item of Array.from(MetaList)) {
        const name = item.alt
        // if (item.value.trim().length > 1) Object.defineProperty(tempDate, name, {value: item.value.trim()})
        if (item.value.trim().length > 0) {
          await DB.template.where('name').equals('content.opf').modify((value, ref) => {
            ref.value.source = ref.value.source.replace(new RegExp(type[ name ]), `${item.value.trim()}`)
          })
        }
      }
    }

    async function addLicense () {
      const LicenseText: string = containerForm.slides[ containerForm.activeIndex ]
                                            .getElementsByTagName('textarea')[0].value.trim()
      const LicensePha: string = LicenseText.replace(/\n/g,'</p><p>').replace(/(.+)/,`<div id = 'license'><p>$1</p><div>`)
      // Object.defineProperty(tempDate, 'license', {value: LicensePha})
      await DB.template.where('name').equals('License.xhtml').modify((value, ref) => {
        ref.value.source.replace(/inori_license/, `${LicensePha}`)
      })
      // 读取当前播放顺序
      let playOrder = await DB.tempOrder.get('play').then((item) => item.source)
      // 播放顺序自增
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })

      let manifest = `<item id="License.xhtml" href="Text/License.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="License.xhtml"/>`
      let ncx = `<navPoint id="License" playOrder="${playOrder}">
                   <navLabel>
                     <text>授权信息</text>
                   </navLabel>
                   <content src="Text/License.xhtml"/>
                 </navPoint>`.trim()

      // 尾添定义
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = value.source += manifest
      })
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = value.source += spine
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source += ncx
      })

      // xmlgen添加完了就添加对应的zipfile
      const licenseXHTML = await DB.template.where('name').equals('License.xhtml').first()
      zip.file(licenseXHTML.path.substr(1), licenseXHTML.source)
    }

    async function addSummary () {
      const SummaryText: string = containerForm.slides[ containerForm.activeIndex ]
                                  .getElementsByTagName('textarea')[0].value.trim()
      const SummatyPha: string = SummaryText.replace(/\n/g, '</p><p>').replace(/(.+)/,`<div id = 'license'><p>$1</p><div>`)
      // Object.defineProperty(tempDate, 'summary', {value: SummatyPha})
      await DB.template.where('name').equals('Summary.xhtml').modify((value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_summary/, `${SummatyPha}`)
      })

      // 读取当前播放顺序
      let playOrder = await DB.tempOrder.get('play').then((item) => item.source)
      // 播放顺序自增
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })

      let manifest = `<item id="Summary.xhtml" href="Text/Summary.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="Summary.xhtml"/>`
      let ncx = `<navPoint id="Summary" playOrder="${playOrder}">
                   <navLabel>
                     <text>简介</text>
                   </navLabel>
                   <content src="Text/Summary.xhtml"/>
                 </navPoint>`.trim()

      // 尾添定义
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = value.source += manifest
      })
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = value.source += spine
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source += ncx
      })

      // xmlgen添加完了就添加对应的zipfile
      const SummaryXHTML = await DB.template.where('name').equals('Summary.xhtml').first()
      zip.file(SummaryXHTML.path.substr(1), SummaryXHTML.source)
    }

    async function addColor () {
      // 读取当前彩图顺序
      let colorOrder = await DB.tempOrder.get('color').then((item) => item.source)
      let colorOrderText = colorOrder > 9
                              ? `0${colorOrder}`
                              : `00${colorOrder}`

      // 修改图片name，储存用作文件名
      let activeTitle = galleryTopObj.slides[galleryTopObj.activeIndex].title
      let activeImg = await DB.allIMG.where('name').equals(activeTitle).first()
      activeImg.name = `Color${colorOrderText}`
      await DB.allIMG.put(activeImg)

      // 彩图顺序自增
      await DB.tempOrder.where('name').equals('color').modify( (value, ref) => {
        ref.value.source++
      })

      // 生成彩图页面
      await DB.template.where('name').equals('Color001.xhtml').modify( (value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_color_name_ext/,`${activeImg.name}.${activeImg.ext}`)
      })

      // 读取当前播放顺序
      let playOrder = await DB.tempOrder.get('play').then((item) => item.source)
      // 播放顺序自增
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })

      let manifest = `<item id="Color${colorOrderText}.xhtml" href="Text/Color${colorOrderText}.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="Color${colorOrderText}.xhtml"/>`
      let ncx = `<navPoint id="Color${colorOrderText}" playOrder="${playOrder}">
                   <navLabel>
                     <text>彩页${colorOrderText}</text>
                   </navLabel>
                   <content src="Text/Color${colorOrderText}.xhtml"/>
                 </navPoint>`.trim()
      // xmlgen添加完了就添加对应的zipfile
      const colorXHTML = await DB.template.where('name').equals('Color001.xhtml').first()
      zip.file(`OEBPS/Text/Color${colorOrderText}.xhtml`, colorXHTML.source)

      const contentText: string = containerForm.slides[containerForm.activeIndex].getElementsByTagName('textarea')[0].value
      if (contentText.length > 0) {
        // contentText.match(/\n/g)
        const contentTextPha: string = contentText.replace(/\n/g,'</p><p>').replace(/(.+)/,`<div id = 'color${colorOrderText}'><p>$1</p><div>`)
        // Object.defineProperty(tempDate, 'solorSummary', {value: SummatyPha})
        // 生成彩图页面
        await DB.template.where('name').equals('Color001-1.xhtml').modify( (value, ref) => {
          ref.value.source = ref.value.source.replace(/inori_color_summary/,`${contentTextPha}`)
        })

        // 播放顺序本地自增
        playOrder++
        // 播放顺序自增
        await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
          ref.value.source++
        })

        manifest += `<item id="Color${colorOrderText}-1.xhtml" href="Text/Color${colorOrderText}-1.xhtml" media-type="application/xhtml+xml"/>`
        spine += `<itemref idref="Color${colorOrderText}-1.xhtml"/>`
        ncx += `<navPoint id="Color${colorOrderText}-1" playOrder="${playOrder}">
                 <navLabel>
                   <text>彩页${colorOrderText}</text>
                 </navLabel>
                 <content src="Text/Color${colorOrderText}-1.xhtml"/>
               </navPoint>`.trim()
        // xmlgen添加完了就添加对应的zipfile
        const colorSumXHTML = await DB.template.where('name').equals('Color001-1.xhtml').first()
        zip.file(`OEBPS/Text/Color${colorOrderText}-1.xhtml`, colorSumXHTML.source)
      }

      // 尾添定义
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = value.source += manifest
      })
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = value.source += spine
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source += ncx
      })
    }

    async function addContents () {
      // 读取当前播放顺序
      let playOrder = await DB.tempOrder.get('play').then((item) => item.source)
      // 播放顺序自增
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })

      // 图片改名
      let activeTitle = galleryTopObj.slides[galleryTopObj.activeIndex].title
      let activeImg = await DB.allIMG.where('name').equals(activeTitle).first()
      activeImg.name = 'Contents'
      await DB.allIMG.put(activeImg)

      // 目录图片页本体
      let manifest = `<item id="Contents-img.xhtml" href="Text/Contents-img.xhtml" media-type="application/xhtml+xml"/>`
      let spine = `<itemref idref="Contents-img.xhtml"/>`
      let ncx = `<navPoint id="Contents-img" playOrder="${playOrder}">
                   <navLabel>
                     <text>目录</text>
                   </navLabel>
                   <content src="Text/Contents-img.xhtml"/>
                 </navPoint>`.trim()
      // 目录页本体
      playOrder++
      await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
        ref.value.source++
      })
      manifest += `<item id="Contents.xhtml" href="Text/Contents.xhtml" media-type="application/xhtml+xml"/>`
      spine += `<itemref idref="Contents.xhtml"/>`
      ncx += `<navPoint id="Contents" playOrder="${playOrder}">
                   <navLabel>
                     <text>目录</text>
                   </navLabel>
                   <content src="Text/Contents.xhtml"/>
                 </navPoint>`.trim()

      // 各章节制作
      let contentItem: HTMLCollectionOf<HTMLInputElement> = containerForm.slides[containerForm.activeIndex]
                                                            .getElementsByClassName('contentItemWrap')[0]
                                                            .getElementsByTagName('input')
      /** 起始值：1 */
      let secOrder = await DB.tempOrder.get('sec').then((item) => item.source)
      let contents = ''
      for (const item of Array.from(contentItem)) {
        if (item.value.trim().length > 0) {
          let PhaSource = await DB.allText.filter((Pha) => new RegExp(item.value.trim()).test(Pha.source))
                                          .first()
          PhaSource.title = item.value.trim()
          DB.allText.put(PhaSource)
          // Object.defineProperty(tempDate, 'content', {value: item.value.trim()})
          // 写入章节本体
          await DB.template.where('name').equals('Section001.xhtml').modify((value, ref) => {
            ref.value.source = ref.value.source.replace(/inori_sec_title/, `${item.value.trim()}`)
                                    .replace(/inori_sec/, `${PhaSource.source}`)
          })

          // 播放序本地自增
          playOrder++

          let secOrderText = secOrder > 9
                              ? `0${secOrder}`
                              : `00${secOrder}`
          let title = item.value.trim()
          // 添加目录页章节标题
          contents += `<div class="mulu"><a class="no-d" href="../Text/Section${secOrderText}.xhtml">${title}</a></div>`

          manifest += `<item id="Section${secOrderText}.xhtml" href="Text/Section${secOrderText}.xhtml" media-type="application/xhtml+xml"/>`
          spine += `<itemref idref="Section${secOrderText}.xhtml"/>`
          ncx += `<navPoint id="Section${secOrderText}" playOrder="${playOrder}">
                    <navLabel>
                      <text>章节${secOrderText} - ${title}</text>
                    </navLabel>
                    <content src="Text/Section${secOrderText}.xhtml"/>
                  </navPoint>`.trim()
          const SectionXHTML = await DB.template.where('name').equals('Section001.xhtml').first()
          zip.file(`OEBPS/Text/Section${secOrderText}.xhtml`, SectionXHTML.source)
          // 最后才自增
          // 章节序本地自增
          secOrder++
          // 章节序自增
          await DB.tempOrder.where('name').equals('sec').modify( (value, ref) => {
            ref.value.source++
          })

          // 播放序自增
          await DB.tempOrder.where('name').equals('play').modify( (value, ref) => {
            ref.value.source++
          })
        }
      }

      // 写入目录页
      await DB.template.where('name').equals('contents.xhtml').modify((value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_contents/, `${contents}`)
      })
      // 写入目录页到zip
      // xmlgen添加完了就添加对应的zipfile
      const contentsXHTML = await DB.template.where('name').equals('contents.xhtml').first()
      zip.file(contentsXHTML.path.substr(1), contentsXHTML.source)
      const contentsIMGXHTML = await DB.template.where('name').equals('contents-img.xhtml').first()
      zip.file(contentsIMGXHTML.path.substr(1), contentsIMGXHTML.source)

      // 写入图片
      await DB.allIMG.each(async item => {
        const imgSource = item.source
        const imgName = item.name
        const imgExt = item.ext
        const imgMime = item.mime
        const imgItem = `<item href="Images/${imgName}.${imgExt}" id="${imgName}.${imgExt}" media-type="${imgMime}" />`
        manifest += imgItem
        zip.file(`OEBPS/Images/${imgName}.${imgExt}`, item.source)
      })
      await DB.template.where('name').equals('contents.xhtml').modify((value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_contents/, `${contents}`)
      })

      // 尾添定义
      await DB.XMLGen.where('name').equals('opfManifest').modify( (value, ref) => {
        ref.value.source = value.source += manifest
      })
      await DB.XMLGen.where('name').equals('opfSpine').modify( (value, ref) => {
        ref.value.source = value.source += spine
      })
      await DB.XMLGen.where('name').equals('ncx').modify( (value, ref) => {
        ref.value.source = value.source += ncx
      })

      // 全部添加完毕，XMLGen写入模板中
      let opfManifest = await DB.XMLGen.get('opfManifest')
      let opfSpine = await DB.XMLGen.get('opfSpine')
      let ncxGen = await DB.XMLGen.get('ncx')
      await DB.template.where('name').equals('content.opf').modify( (value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_manifest/, `${opfManifest.source}`)
                                            .replace(/inori_time/, `${Realdate}`)
                                            .replace(/inori_uuid/, `${Realuuid}`)
                                            .replace(/inori_spine/, `${opfSpine.source}`)
      })
      await DB.template.where('name').equals('toc.ncx').modify( (value, ref) => {
        ref.value.source = ref.value.source.replace(/inori_ncx/, `${ncxGen.source}`)
      })
      // 写入opf到zip
      const ZIPOPF = await DB.template.where('name').equals('content.opf').first()
      zip.file(`OEBPS/content.opf`, ZIPOPF.source)
      // 写入ncx到zip
      const ZIPNCX = await DB.template.where('name').equals('toc.ncx').first()
      zip.file(`OEBPS/toc.ncx`, ZIPNCX.source)
      swiperH.slideNext()
      await downloadReady()

    }

    let customEventID = {
      addCover,
      addCoverAlt,
      addMetadate,
      addLicense,
      addSummary,
      addColor,
      addColorLast: addColor,
      addContents
    } as {
      [index: string]: () => Promise<void>
    }
    let targetID: keyof typeof customEventID = target.id || undefined
    if ( customEventID[ targetID ] ) await customEventID[ targetID ]()

    // 翻页逻辑
    if (target.className === 'addButton') {
      // 需要添加彩页
      containerForm.appendSlide(colorSlide)
      galleryTopObj.slideNext()// 相互控制的原因所以触发一次就够了
      containerForm.slideNext()

    } else if ( target.className === 'button') {
      // 常规跳转，需要图片同步跳转
      galleryTopObj.slideNext()
      containerForm.slideNext()

    } else if ( target.className === 'button_noimg' || target.id === 'addMetadate') {
      // 下一页没有图片，直接跳转
      containerForm.slideNext()

    } else if ( target.className === 'color_last_button') {
      // 添加目录
      containerForm.appendSlide(contentSlide)
      galleryTopObj.slideNext()
      // 目录条目添加逻辑
      document.getElementsByClassName('contentItemWrap')[0].addEventListener('click', (event) => {
        let target = event.target as typeof event.target & { nodeName: string, parentElement: HTMLElement, nextElementSibling: HTMLElement | null }
        if (target.nodeName.toLocaleUpperCase() === 'INPUT' && target.nextElementSibling === null) {
          let newInput = new ContentItemInput().creat()
          target.parentElement.appendChild(newInput)
          // newInput.focus()
        }
      })
      containerForm.slideNext()
    }

  })
}

async function downloadReady () {
  //
  let downloadEle = document.getElementsByClassName('download ')[0]
  let downloadLink = downloadEle.getElementsByTagName('a')[0]
  zip.generateAsync({type: 'blob'})
  .then(function (blob) {
    downloadLink.innerText = '制作完成'
    downloadLink.href = URL.createObjectURL(blob)
    try {
      saveAs(blob, 'hello.zip')
    } catch (error) {
      console.log(error)
    }
  })
}

browser.runtime.onConnect.addListener(function (port: any) {
  if (port.name === 'progress') {
    port.onMessage.addListener((msg: {name: string, type: 'fetch' | 'storage' | string}) => {
      // {type: '', name: ''}
      if (msg.type === 'fetch') HTMLEle.progress.textContent = `正在读取图片：${msg.name}`
      else if (msg.type === 'storage') HTMLEle.progress.textContent = `正在保存文本：${msg.name}`
    })
  } else if (port.name === 'BGAllDone') {
    making()
  } else if (port.name === 'error') {
    port.onMessage.addListener((msg: string) => {
      console.error(msg)
    })
  }
})
